package com.zc.im.service.im.group.impl;

import com.github.pagehelper.PageHelper;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.zc.im.mapper.im.group.ZcImUnreadNumMapper;
import com.zc.im.model.im.group.ZcImMsgHistoryModel;
import com.zc.im.model.im.group.ZcImUnreadNum;
import com.zc.im.model.im.group.ZcImUnreadNumExample;
import com.zc.im.service.im.group.ImMsgHistoryService;
import com.zc.im.service.im.group.ImUnreadNumService;
import com.zc.im.util.ImGolbalTypeContext;
import com.zc.im.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/7/12.
 */
@Service
public class ImUnreadNumServiceImpl implements ImUnreadNumService {


    @Autowired
    private ZcImUnreadNumMapper zcImUnreadNumMapper;
    @Autowired
    private ImMsgHistoryService msgHistoryService;

    private Logger logger  = Logger.getLogger(ImUnreadNumServiceImpl.class);

    /**
     * 保存或者更新未读消息数量
     * 2017-7-12 11:17:05
     * @param
     * @return
     */
    public Integer saveOrUpdateUnreadNum(Integer userId, Integer targetObjId, String type, String sendUserType){
        Integer backStatus = 0;
        if(userId == null || targetObjId == null || StringUtils.isEmpty(type)){
            return backStatus;
        }
        ZcImUnreadNum unreadNum = findUnreadNum(userId, targetObjId, type);
        if(unreadNum == null || unreadNum.getId() == 0){
            insertUnreadNum(userId, targetObjId, type, sendUserType);
        }else if(unreadNum.getId()!= null){
            ZcImUnreadNumExample unreadNumExample = new ZcImUnreadNumExample();
            ZcImUnreadNumExample.Criteria criteria = unreadNumExample.createCriteria();
            criteria.andSendUserIdEqualTo(userId);
            criteria.andTypeEqualTo(type);
            criteria.andTargetObjIdEqualTo(targetObjId);

            ZcImUnreadNum modifyUnreadNum = new ZcImUnreadNum();
            modifyUnreadNum.setUnreadNum(unreadNum.getUnreadNum() + 1);

            zcImUnreadNumMapper.updateByExampleSelective(modifyUnreadNum, unreadNumExample);
        }
        return backStatus;
    }


    public Integer updateUnreadNumToDef(Integer userId, Integer targetObjId, String type){
        Integer backKey = 0;
        if(userId == null || targetObjId == null || StringUtils.isEmpty(type)){
            return backKey;
        }
        ZcImUnreadNumExample unreadNumExample = new ZcImUnreadNumExample();
        ZcImUnreadNumExample.Criteria criteria = unreadNumExample.createCriteria();
        criteria.andSendUserIdEqualTo(userId);
        criteria.andTypeEqualTo(type);
        criteria.andTargetObjIdEqualTo(targetObjId);

        ZcImUnreadNum record = new ZcImUnreadNum();
        record.setSendUserId(userId);
        record.setType(type);
        record.setTargetObjId(targetObjId);
        record.setUnreadNum(0);


        //更新消息至已读
        ZcImMsgHistoryModel msgHistoryCriteria = new ZcImMsgHistoryModel();
        msgHistoryCriteria.setMsgAgreementType(type);
        msgHistoryCriteria.setSourceObjId(userId);
        msgHistoryCriteria.setTargetObjId(targetObjId);
        msgHistoryCriteria.setMsgReadStatus(ImGolbalTypeContext.IM_MSG_READ_STATUS_READ);
        msgHistoryService.updateMsgHistory(msgHistoryCriteria);
        backKey = zcImUnreadNumMapper.updateByExampleSelective(record, unreadNumExample);
        return backKey;
    }


    /**
     * 查询未读数
     * 2017-7-15 19:29:11
     * @param userId
     * @param type
     * @return
     */
    public ZcImUnreadNum findUnreadNum(Integer userId, Integer targetObjId, String type){
        ZcImUnreadNum unreadNum = null;
        if(userId == null || targetObjId == null || StringUtils.isEmpty(type)){
            return unreadNum;
        }
        ZcImUnreadNumExample unreadNumExample = new ZcImUnreadNumExample();
        ZcImUnreadNumExample.Criteria criteria =  unreadNumExample.createCriteria();

        criteria.andSendUserIdEqualTo(userId);
        criteria.andTypeEqualTo(type);
        criteria.andTargetObjIdEqualTo(targetObjId);

        List<ZcImUnreadNum> unreadNums = zcImUnreadNumMapper.selectByExample(unreadNumExample);
        if(unreadNums == null || unreadNums.size() == 0){
            return unreadNum;
        }
        unreadNum = unreadNums.get(0);
        return unreadNum;
    }


    /**
     * 添加IM未读数
     * 2017-7-15 19:39:38
     * @param userId
     * @param type
     * @return
     */
    public ZcImUnreadNum insertUnreadNum(Integer userId, Integer targetObjId, String type, String sendUserType){
        ZcImUnreadNum zcImUnreadNum = null;
        if(userId == null || StringUtils.isEmpty(type) || targetObjId == null){
            return zcImUnreadNum;
        }

        ZcImUnreadNum unreadNum = findUnreadNum(userId, targetObjId, type);
        if(unreadNum!= null){
            return unreadNum;
        }
            zcImUnreadNum =  new ZcImUnreadNum();
            zcImUnreadNum.setType(type);
            zcImUnreadNum.setSendUserId(userId);
            zcImUnreadNum.setTargetObjId(targetObjId);
            zcImUnreadNum.setUnreadNum(0);
            zcImUnreadNum.setStartTime(new Date());
            zcImUnreadNum.setEndTime(new Date());
            zcImUnreadNum.setStatus(ImGolbalTypeContext.STATUS_VALID);
            zcImUnreadNum.setSendUserType(sendUserType);
            Integer inserKey = insertSelective(zcImUnreadNum);
        if (inserKey == 1) {
            ZcImUnreadNum zcImUnreadNumtwo = new ZcImUnreadNum();
            zcImUnreadNumtwo.setType(type);
            zcImUnreadNumtwo.setSendUserId(targetObjId);
            zcImUnreadNumtwo.setTargetObjId(userId);
            zcImUnreadNumtwo.setUnreadNum(0);
            zcImUnreadNumtwo.setStartTime(new Date());
            zcImUnreadNumtwo.setEndTime(new Date());
            zcImUnreadNumtwo.setStatus(ImGolbalTypeContext.STATUS_VALID);
            zcImUnreadNumtwo.setSendUserType(sendUserType);
            insertSelective(zcImUnreadNumtwo);
        }else {
            logger.error("添加未读失败");
        }
        return zcImUnreadNum;
    }


    private Integer insertSelective(ZcImUnreadNum zcImUnreadNum) {
        Integer insertSelectiveKey = null;
        if (zcImUnreadNum == null) {
            return insertSelectiveKey;
        }
        try {
         insertSelectiveKey = zcImUnreadNumMapper.insertSelective(zcImUnreadNum);
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
         return insertSelectiveKey;
    }
    public List<ZcImUnreadNum> queryUnreadNumByUser(Integer userId, String type, Integer unreadNum){
        List<ZcImUnreadNum> unreadNums = new ArrayList<>();
        if(userId == null){
            return unreadNums;
        }
        ZcImUnreadNum criteria = new ZcImUnreadNum();
        criteria.setSendUserId(userId);
        criteria.setType(type);
        criteria.setUnreadNum(unreadNum);
        criteria.setOrderByClause(" end_time desc");
        unreadNums = zcImUnreadNumMapper.selectUnreadNumByExample(criteria);
        return unreadNums;
    }


    /**
     * 查询最近的聊天消息在聊天记录表中
     * 2017-7-16 15:33:44
     * @return
     */
    public List<ZcImUnreadNum> queryLatelyImNotInUnread(Integer userId, String type, Integer pageSize, Integer pageNum){
        List<ZcImUnreadNum> imUnreadNums = new ArrayList<>();
        ZcImUnreadNumExample unreadNumExample = new ZcImUnreadNumExample();
        ZcImUnreadNumExample.Criteria criteria =  unreadNumExample.createCriteria();
        if(userId!= null){
            criteria.andTargetObjIdEqualTo(userId);
        }
        if(!StringUtils.isEmpty(type)){
            criteria.andTypeEqualTo(type);
        }
        criteria.andUnreadNumEqualTo(0);
        unreadNumExample.setOrderByClause(" end_time desc");
        PageHelper.startPage(pageNum, pageSize);
        imUnreadNums = zcImUnreadNumMapper.selectByExample(unreadNumExample);
        return imUnreadNums;
    }
}
